package com.snsoft.katalk;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;

import kr.co.withmob.withmobsdk.WithMob;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.webkit.MimeTypeMap;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.*;

import net.daum.adam.publisher.AdView;
import net.daum.adam.publisher.AdView.OnAdClickedListener;
import net.daum.adam.publisher.AdView.OnAdClosedListener;
import net.daum.adam.publisher.AdView.OnAdFailedListener;
import net.daum.adam.publisher.AdView.OnAdLoadedListener;
import net.daum.adam.publisher.AdView.OnAdWillLoadListener;
import net.daum.adam.publisher.impl.AdError;
import net.daum.adam.publisher.AdView.AnimationType;

public class KaTalkActivity extends Activity {
	public WebView wv;
	public Dialog dialog;
	private String wvurl = "";
    private ProgressDialog mProgressDialog;
	public File f; 
	
	public String actiontype;
	
	private static final int SELECT_IMAGE = 100;
	public static final int DIALOG_QUIT_ALERT = 1;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	
    private com.google.ads.AdView admobView = null;
	private net.daum.adam.publisher.AdView adamView = null;
	private static final String LOGTAG = "Adam";
	
	private String param = "";
	private String param_temp = "";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Activity activity = this; 
        
        setContentView(R.layout.main);
        
        wv = (WebView)findViewById(R.id.webview);
        
        wv.getSettings().setJavaScriptEnabled(true);
        wv.getSettings().setLoadsImagesAutomatically(true);
        wv.getSettings().setLightTouchEnabled(true);
        wv.getSettings().setPluginsEnabled(true);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setVerticalScrollbarOverlay(true);

        wv.setBackgroundColor(Color.BLACK);
        
        // Loading dialog set
        dialog = new Dialog(this, R.style.SNDialog);
        dialog.addContentView(new ProgressBar(this), new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        
        wv.setWebViewClient(new WebViewClient()
        {
        	// Webview handler
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url)
        	{
        		// 한글인코딩
        		try{ url = URLDecoder.decode(url, "UTF-8"); }catch(Exception e){} 
        		
        		// 다운로드 후 처리를 위해 사용.
        		actiontype = url;
    			String sd = Environment.getExternalStorageDirectory().toString();
				File path = new File(sd + "/KaTalk");
								
				if(url.startsWith("http://season"))
        		{        			                	
                	param = url.substring(url.indexOf("#") + 1);
        			
        			Intent itDetail = new Intent(getApplication(), KaTalkDetail.class);
        			itDetail.putExtra("JSON_URL", "http://picasaweb.google.com/data/feed/api/user/snkatalk@gmail.com/albumid/" + param.split("@")[0] + "?alt=jsonc&kind=photo&max-results=100&orderby=published");
        			itDetail.putExtra("TOTAL", Integer.parseInt(param.split("@")[1]));
        			
                	startActivity(itDetail);
                	
                	overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
        		}
				else if(url.startsWith("http://send"))
				{
        			String action = Intent.ACTION_PICK;
        	        Uri uri = android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI;
        	        Intent itGallery = new Intent(action, uri);
        	        startActivityForResult(itGallery, SELECT_IMAGE);
				}
				else if(url.startsWith("katalk://"))
        		{					
            		try {
						onKatalk(url.split("@")[1], url.split("@")[0], url.split("@")[0].substring(9), url.split("@")[2]);
					} catch (NameNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        		}
				else if(url.startsWith("http://lotto"))
				{			        
					onShare(new File(Environment.getExternalStorageDirectory().toString() + "/KaTalk/lotto.png"));
				}
				else if(url.startsWith("market://"))
				{

					Intent intent = new Intent(Intent.ACTION_VIEW); 
					intent.setData(Uri.parse(url)); 
					startActivity(intent);
				}
				else if(url.startsWith("http://save") || url.startsWith("http://share"))
        		{
        			String pcsurl = param;
        			Log.d("url:", param);
        			
        			String pcsfn = pcsurl.substring(pcsurl.lastIndexOf("/") + 1);
    				File fn = new File(path, pcsfn);
    				
    				if(!path.isDirectory()) 
    				{
    					path.mkdirs();
    				}
    				
        			if(fn.isFile())
    				{
    					if(url.startsWith("http://save"))
    						Toast.makeText(activity, "동일한 파일이 이미 존재합니다.", Toast.LENGTH_LONG).show();
    					else if(url.startsWith("http://share"))
    						onShare(fn);
    				}
    				else
    				{
    					if(dialog != null)
    	        			dialog.show();

    					new DownloadFileAsync().execute(pcsurl, pcsfn);
    				}
        		}
				else if(url.startsWith("event://"))
				{
					WithMob withMob = new WithMob();
					withMob.openWithMob(KaTalkActivity.this);

				}
				else if(url.indexOf("?") > 0)
        		{
        			param = url.substring(url.indexOf("?") + 1);
        			view.loadUrl(url.substring(0, url.indexOf("?")));
        			
        			if(url.matches(".*jjal_funny.*"))
        				param_temp = param;
        		}
				else
        		{        	
					// 이전 페이지 파라미터 설정
	    			param = param_temp;
	    			
        			view.loadUrl(url);
        		}
				
        		return true;
        	}
        	
        	
        	@Override     
        	public void onPageStarted(WebView view, String url, Bitmap favicon) 
        	{
        		if(dialog != null)
        			dialog.show();
        	} 
        	
        	@Override     
        	public void onPageFinished(WebView view, String url) 
        	{
        		wvurl = wv.getUrl();
        		
        		if(dialog != null && dialog.isShowing())
        		{
        			dialog.dismiss();
        		}
        		
        		if(!wvurl.equals("") && url.matches(".*jjal.*"))
        		{
        			view.loadUrl("javascript:Load('" + param + "');");
        		}
        	}      
        	
        	@Override
        	public void onReceivedError(WebView view, int errorCode,String description, String failingUrl)
        	{
        		wv.loadData("<html><body align='center' valign='center'></body></html>", "text/html", "UTF-8");
        		Toast.makeText(activity, "Network unavailable. Please try again later.", Toast.LENGTH_LONG).show();
        	}
        });
        
        wv.loadUrl("file:///android_asset/index.html");
        
        // adam 실행
        initAdam();
        
        // Admob Setting
        admobView = (com.google.ads.AdView)this.findViewById(R.id.admobView);
        AdRequest adRequest = new AdRequest();
        //adRequest.addTestDevice(AdRequest.TEST_EMULATOR);					// Emulator
        //adRequest.addTestDevice("444673C1328A36BB3EB297C2A231C68B");		// Test Android Device
        admobView.loadAd(adRequest);
        
        admobView.setAdListener(new AdListener() 
        {
        	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) 
        	{
			}

			public void onDismissScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onLeaveApplication(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onPresentScreen(Ad arg0) {
				// TODO Auto-generated method stub
				
			}

			public void onReceiveAd(Ad arg0) {
				// TODO Auto-generated method stub
			}

        });
        
        // Setup
        copyResources(R.raw.lotto, "png");
    }
    
    private void initAdam() 
    {
		// Ad@m sdk 초기화 시작
    	adamView = (AdView) findViewById(R.id.adamView);

		// 광고 클릭시 실행할 리스너
    	adamView.setOnAdClickedListener(new OnAdClickedListener() {
			public void OnAdClicked() {
				Log.i(LOGTAG, "광고를 클릭했습니다.");
			}
		});

		// 광고 내려받기 실패했을 경우에 실행할 리스너
    	adamView.setOnAdFailedListener(new OnAdFailedListener() {
			public void OnAdFailed(AdError arg0, String arg1) {
				//Log.w(LOGTAG, arg1);
				
				admobView.setVisibility(View.VISIBLE);			// 애드몹 표시
				admobView.bringToFront();						// 애드몹 상위
			}
		});

		// 광고를 정상적으로 내려받았을 경우에 실행할 리스너
    	adamView.setOnAdLoadedListener(new OnAdLoadedListener() {
			public void OnAdLoaded() {
				Log.i(LOGTAG, "광고가 정상적으로 로딩되었습니다.");
				
				admobView.setVisibility(View.GONE);				// 애드몹 숨김
				adamView.bringToFront();						// 아담 상위
				
				
			}
		});

		// 광고를 불러올때 실행할 리스너
    	adamView.setOnAdWillLoadListener(new OnAdWillLoadListener() {
			public void OnAdWillLoad(String arg1) {
				Log.i(LOGTAG, "광고를 불러옵니다. : " + arg1);
			}
		});

		// 광고를 닫았을때 실행할 리스너
    	adamView.setOnAdClosedListener(new OnAdClosedListener() {
			public void OnAdClosed() {
				Log.i(LOGTAG, "광고를 닫았습니다.");
			}
		});

		// 할당 받은 clientId 설정
    	adamView.setClientId("2eecZ4xT138084bb5fd");	// Play
    	//adamView.setClientId("2eedZ4yT138084d2b65");	// Tstore
    	
    	adamView.setRequestInterval(12);

		// Animation 효과 : 기본 값은 AnimationType.NONE
    	adamView.setAnimationType(AnimationType.FLIP_HORIZONTAL);

    	adamView.setVisibility(View.VISIBLE);
	}
    
    // Back key setting
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
    	if(keyCode == KeyEvent.KEYCODE_BACK)
    	{
    		if(!wvurl.matches(".*index.*") && wv.canGoBack())
        	{
    			if(wvurl.matches(".*jjal_sub.*"))
    			{
    				// 이전 페이지 파라미터 설정
	    			param = param_temp;
    				wv.loadUrl("file:///android_asset/jjal_funny.html");
    			}
    			else
    				wv.loadUrl("file:///android_asset/index.html");
    			
        		return true;
        	}
    		else
    		{
    			showDialog(DIALOG_QUIT_ALERT);
	    		return true;
    		}
    	}
    	return super.onKeyDown(keyCode, event);
    }

    // Screen rotating fix
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    @Override
	public void onDestroy() {
		super.onDestroy();

		if (admobView != null) 
		{
			admobView.destroy();
			admobView = null;
		}
		
		if (adamView != null) 
		{
			adamView.destroy();
			adamView = null;
		}
	}
    
    // File Copy
    private boolean copyFile(FileInputStream fis , FileOutputStream newfos)
    {
        boolean result = false;
            try 
            {
                int readcount=0;
                byte[] buffer = new byte[1024];
                while((readcount = fis.read(buffer,0,1024))!= -1)
                {
                    newfos.write(buffer,0,readcount);
                }
                
                newfos.close();
                fis.close();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            result = true;

        return result;
    }
    
    // Selected Gallery & Send Mail
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == SELECT_IMAGE) 
        {
            if (resultCode == Activity.RESULT_OK) 
            {
                Uri selectedImage = data.getData();
                // TODO Do something with the select image URI
                String[] arrSendMail = {"snkatalk@gmail.com"}; 
                Intent itSendMail = new Intent(Intent.ACTION_SEND);  
                itSendMail.putExtra(Intent.EXTRA_EMAIL, arrSendMail); 
                itSendMail.putExtra(Intent.EXTRA_SUBJECT, "카톡ㅋㅋㅋ 올리기");  
                itSendMail.putExtra(Intent.EXTRA_TEXT, "");   
                itSendMail.putExtra(Intent.EXTRA_STREAM, selectedImage);  
                //itSendMail.setType("image/*"); 
                itSendMail.setType("message/rfc822");
                startActivity(Intent.createChooser(itSendMail, "E-Mail 어플리케이션을 선택하세요."));
            }
        }
    }
    
    // Share
    public void onShare(File fn)
    {
		
		Intent intent = new Intent(Intent.ACTION_SEND);
		
		intent.setType("image/png");
		
		intent.putExtra(Intent.EXTRA_STREAM,  Uri.fromFile(fn));
		intent.putExtra(Intent.EXTRA_TEXT, "[출처]카톡ㅋㅋㅋ"); 
		intent.setPackage("com.kakao.talk");
		
		startActivity(intent);
    }
    
    // Image Download
    class DownloadFileAsync extends AsyncTask<String, String, String> 
    {
        
		@Override
		protected void onPreExecute() 
		{
			super.onPreExecute();
			//showDialog(DIALOG_DOWNLOAD_PROGRESS);
		}

        @Override
        protected String doInBackground(String... aurl) 
        {
            int count;

            try 
            {
                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                
                String sd = Environment.getExternalStorageDirectory().toString();
                
				File path = new File(sd + "/KaTalk");
				
				if(!path.isDirectory()) 
				{
					path.mkdirs();
				}
       	     
    			String fn = aurl[1];
    			f = new File(path, fn);

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(f.getAbsolutePath());

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) 
                {
                    total += count;
                    //publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
            } catch (Exception e) {}
            return aurl[1];

        }
        
        protected void onProgressUpdate(String... progress) 
        {
             Log.d("ANDRO_ASYNC",progress[0]);
             //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String fn) 
        {
        	dialog.dismiss();
        	
            //removeDialog(DIALOG_DOWNLOAD_PROGRESS);
        	if(actiontype.startsWith("http://save"))
        	{
        		Toast.makeText(KaTalkActivity.this, "파일을 저장하였습니다.", Toast.LENGTH_LONG).show();
        		// media center 새로고침
        		//sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
        		sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+ Environment.getExternalStorageDirectory() + "/KaTalk/" + fn)));
        	}
        	else if(actiontype.startsWith("http://share"))
        		onShare(f);
        }
    }
    
    
    
    // Dialog Management
    @Override
    protected Dialog onCreateDialog(int id) 
    {
    	super.onCreateDialog(id);
    	
        switch (id) 
        {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("이미지 저장 중..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                return mProgressDialog;
            case DIALOG_QUIT_ALERT:
            	new AlertDialog.Builder(this)
    			.setMessage("카톡ㅋㅋㅋ를 종료하시겠습니까?")
    			.setPositiveButton("확인", new DialogInterface.OnClickListener()
    			{
					public void onClick(DialogInterface dialog, int which) 
					{
						finish();
					}
				})
				.setNegativeButton("취소", null).show();
            	return null;
            default:
                return null;
        }
    }
    
    // 카카오톡 공유
	public void onKatalk(String title, String executeurl, String weburl, String desc) throws NameNotFoundException {
		ArrayList<Map<String, String>> metaInfoArray = new ArrayList<Map<String, String>>();

		// If application is support Android platform.
		Map<String, String> metaInfoAndroid = new Hashtable<String, String>(1);
		metaInfoAndroid.put("os", "android");
		metaInfoAndroid.put("devicetype", "phone");
		metaInfoAndroid.put("installurl", "http://" + weburl);
		metaInfoAndroid.put("executeurl", "http://" + weburl);
		
		// If application is support ios platform.
		Map<String, String> metaInfoIOS = new Hashtable<String, String>(1);
		metaInfoIOS.put("os", "ios");
		metaInfoIOS.put("devicetype", "phone");
		metaInfoIOS.put("installurl", "your iOS app install url");
		metaInfoIOS.put("executeurl", "Link://starActivity");
		
		// add to array
		metaInfoArray.add(metaInfoAndroid);
		metaInfoArray.add(metaInfoIOS);
		
		// Recommended: Use application context for parameter. 
		KakaoLink kakaoLink = KakaoLink.getLink(getApplicationContext());
		
		// check, intent is available.
		if(!kakaoLink.isAvailableIntent()) 
			return;
		
		/**
		 * @param activity
		 * @param url
		 * @param message
		 * @param appId
		 * @param appVer
		 * @param appName
		 * @param encoding
		 * @param metaInfoArray
		 */
		kakaoLink.openKakaoAppLink(
				this, 
				"http://" + weburl, 
				desc,  
				getPackageName(), 
				getPackageManager().getPackageInfo(getPackageName(), 0).versionName,
				title,
				"UTF-8", 
				metaInfoArray);
	}
	
	// 리소스파일 복사
	public void copyResources(int resId, String type)
	{
		String sd = Environment.getExternalStorageDirectory().toString();
        
		File path = new File(sd + "/KaTalk");
		
		if(!path.isDirectory()) 
		{
			path.mkdirs();
		}
		
		InputStream in = getResources().openRawResource(resId);
		String filename = getResources().getResourceEntryName(resId);

		File f = new File(path, filename + "." + type);

		if(!f.isFile())
		{
			try 
			{
				OutputStream out = new FileOutputStream(f);
				byte[] buffer = new byte[1024];
				int len;
				while((len = in.read(buffer, 0, buffer.length)) != -1){
					out.write(buffer, 0, len);
				}
				in.close();
				out.close();
			} catch (FileNotFoundException e) {
				Log.i("Test", "Setup::copyResources - "+e.getMessage());
			} catch (IOException e) {
				Log.i("Test", "Setup::copyResources - "+e.getMessage());
			}
		}
	}
}